package com.tanhua.recommend.job;

import com.tanhua.domain.mongo.Movement;
import com.tanhua.domain.mongo.RecommendMovement;
import com.tanhua.domain.mongo.RecommendUser;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.RandomUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Set;

@Component
public class MovementJob {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MongoTemplate mongoTemplate;


//    @Scheduled(cron = "0 0/30 * * * ?") //每隔30分钟执行
    @Scheduled(cron = "0 * * * * ?") //每隔1分钟执行
    public void syncData(){
//        把redis中的推荐数据放入到mongo
//        把redis中 QUANZI_PUBLISH_RECOMMEND_用户id 中数据 同步到mongo的recommend_movement
        Set<String> keys = redisTemplate.keys("QUANZI_PUBLISH_RECOMMEND_*");
        if(CollectionUtils.isEmpty(keys)){
            return;
        }
        RecommendMovement recommendMovement = null;

        for (String key : keys) {




//            替换获取userId
            String userIdStr = key.replace("QUANZI_PUBLISH_RECOMMEND_","");
            Long userId = Long.parseLong(userIdStr);

//            把之前给这个用户推荐的旧数据删除
            mongoTemplate.remove(new Query(Criteria.where("userId").is(userId)),RecommendMovement.class);


//       key  是     QUANZI_PUBLISH_RECOMMEND_10
            String pidStr = redisTemplate.boundValueOps(key).get();
//            21,4,19,20,26,100099,28,10064,3,10020
            String[] pidArray = pidStr.split(",");

            for (int i = 0; i < pidArray.length; i++) {
                Long pid = Long.parseLong(pidArray[i]);
                // 通过pid查询得到Movement 从对象中获取id
                Movement movement = mongoTemplate.findOne(new Query(Criteria.where("pid").is(pid)), Movement.class);
                if(movement==null){
                    continue;
                }
                recommendMovement = new RecommendMovement();

                recommendMovement.setId(new ObjectId());
                recommendMovement.setPid(pid);
                recommendMovement.setCreated(new Date().getTime()); //这里把实体类中的类型改成Long
                recommendMovement.setUserId(userId);

                recommendMovement.setMovementId(movement.getId()); // 通过pid查询得到Movement 从对象中获取id
                recommendMovement.setScore(RandomUtils.nextDouble(80,99));
                mongoTemplate.save(recommendMovement);
            }




        }





    }

}
